package mysql

import (
	"2207a/bawei/user_srv/appconfig"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"sync"
)

var (
	Db   *gorm.DB
	err  error
	once sync.Once
)

func InitMysql() {
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	mysqlConf := appconfig.AppConf.MySQLConfig
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		mysqlConf.User, mysqlConf.Password, mysqlConf.Host, mysqlConf.Port, mysqlConf.Database)
	once.Do(func() {
		Db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	})
	if err != nil {
		fmt.Println("数据库连接失败", err)
		return
	}
	Db.AutoMigrate(new(User), new(Video))
	fmt.Println("数据库连接成功")
}
